/*********************************************************************
 *
 *  elksip - a multi-platform Sip Phone Server
 *
 *  file: contact.h  sip Msg contact
 *
 *  Copyright 2011-2014 Elksip.
 *
 ********************************************************************/

#include "contact.h"
#include "sip_inc.h"
#include "elk_debug.h"
#include "elk_msg.h"

void elk_contact_init(Elk_Contact *contact)
{
    memset(contact, 0, sizeof(Elk_Contact));
}
void elk_contact_free(Elk_Contact *contact)
{
    if(contact != NULL)
    {
        ELK_FREE(contact->name);
        ELK_FREE(contact->domain);
        ELK_FREE(contact->expires);
    }
}
void elk_contact_cpy(const Elk_Contact *contact, Elk_Contact *dest)
{
    dest->name = elk_strdup(contact->name);
    dest->domain = elk_strdup(contact->domain);
    dest->expires = elk_strdup(contact->expires);
}
void elk_contact_print(Elk_Contact *contact)
{

}

void elk_contact2str(const Elk_Contact *Contact, Elk_string *str)
{
    char buf[128] = {0};
    if(Contact->expires!=NULL)
    {
        snprintf(buf, sizeof(buf), "Contact: <sip:%s@%s>;expires=%s",
            Contact->name, Contact->domain, Contact->expires);
    }else
    {
        snprintf(buf, sizeof(buf), "Contact: <sip:%s@%s>",
            Contact->name, Contact->domain);
    }
    elk_str_append(str, buf);
    elk_str_append_CRLF(str);
}

//Contact: <sip:100@127.0.0.1:37474>
//Contact: <sip:888@192.168.16.87:56476;rinstance=231fd7f3df3cf0c4>
//Contact: *
int  elk_contact_parse(Elk_Message* msg, const char *value)
{
    msg->contact =(Elk_Contact*) ELK_MALLOC(sizeof(Elk_Contact));
    elk_contact_init(msg->contact);
    Elk_Contact *contact = (msg->contact);
    const char *colon_index = strchr(value, ':');
    if(colon_index==NULL)
        return -1;
    const char *art_index = strchr(colon_index, '@');
    if(art_index==NULL)
        return -1;
    int len = art_index-colon_index;
    char buf[64] = {0};
    strncpy(buf, colon_index+1, len-1);
    contact->name = strdup(buf);

    const char *great_index = strchr(art_index, '>');
    if(great_index!=NULL)
        len = great_index - art_index;
    else
        len = strlen(art_index);
    contact->domain = (char*)ELK_MALLOC(len);
    memset(contact->domain, 0, len);
    strncpy(contact->domain, art_index+1, len-1);

    SIP_DEBUG_INFO("zhang  :[%s]\n", contact->domain);
    const char *equal_index = NULL;
    if(great_index!=NULL)
        equal_index = strchr(great_index, '=');
    if(equal_index!=NULL)
    {
        len = strlen(equal_index);
        contact->expires = (char*)ELK_MALLOC(len-1);
        strncpy(contact->expires, equal_index+1, len-2);
    }
    return 0;
    
}

